<?php

namespace app\logic\api\platform;

use app\model\ApiLog;
use app\model\Shop;
use GuzzleHttp\Client;
use think\Exception;

abstract class BaseApi
{
    /**
     * @var string 请求地址
    */
    protected $url;

    /**
     * @var string 请求方式 get|post
    */
    protected $method;

    /**
     * @var string 接口标识
    */
    protected $mark;

    /**
     * @var array 公共参数
    */
    protected $publicParams = [];

    /**
     * @var array 业务参数
    */
    protected $reqParams = [];

    /**
     * @var string 接口原始数据
    */
    protected $repContent;

    /**
     * @var array 解析之后的接口数据
    */
    protected $repData;

    /**
     * @var array 其他设置
    */
    protected $setting = [];

    /**
     * @var array client请求选项
    */
    protected $clientOptions = [];

    /**
     * @var Client 客户端请求对象
    */
    protected $client;

    /**
     * @var Shop 网店
    */
    protected $shop;

    public static function __make(Client $client, Shop $shop) {
        $instance = new static();
        $instance->client = $client;
        $instance->shop = $shop;
        $params = (array)$shop->params;
        $instance->initParams($params);
        return $instance;
    }

    protected function request() {
        $this->buildParams();
        $options = [
            'verify' => false
        ];
        if ($this->method == 'get') {
            $options['query'] = $this->reqParams;
        } else {
            $options['form_params'] = $this->reqParams;
        }
        $options = array_merge($options, $this->clientOptions);

        try {
            $log_data = [
                'customer_id' => $this->shop->customer_id,
                'platform_id' => $this->shop->platform_id,
                'method' => $this->mark,
                'request_params' => var_export($this->reqParams, true),
                'start_time' => time(),
                'status' => 1
            ];

            $this->repContent = $this->client->request($this->method, $this->url, $options)->getBody()->getContents();

            $log_data['response_params'] = $this->repContent;
            $log_data['end_time'] = time();

            $this->parseContent();
        } catch (Exception $e) {
            $log_data['status'] = 0;
            $log_data['response_params'] = $e->getMessage();
            $log_data['end_time'] = time();
        } finally {
            (new ApiLog())->save($log_data);
        }
    }

    /**
     * 发送请求之前组装参数
    */
    abstract protected function buildParams() : void;

    /**
     * 初始化token
    */
    abstract protected function initParams($params);

    /**
     * 解析接口数据
    */
    protected function parseContent() {
        $this->repData = json_decode($this->repContent, true);
    }
}
